package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.github.yulichang.query.MPJQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.service.IClientCrmProjetDetailService;
import com.mdd.admin.validate.ClientCrmProjetDetailCreateValidate;
import com.mdd.admin.validate.ClientCrmProjetDetailUpdateValidate;
import com.mdd.admin.validate.ClientCrmProjetDetailSearchValidate;
import com.mdd.admin.vo.ClientCrmProjetDetailListedVo;
import com.mdd.admin.vo.ClientCrmProjetDetailDetailVo;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.*;
import com.mdd.common.mapper.*;
import com.mdd.common.util.ListUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目基本信息实现类
 *
 * @author LikeAdmin
 */
@Service
public class ClientCrmProjetDetailServiceImpl implements IClientCrmProjetDetailService {

    @Resource
    ClientCrmProjetDetailMapper clientCrmProjetDetailMapper;

    @Resource
    ClientCrmProjetDetailTypeMapper clientCrmProjetDetailTypeMapper;

    @Resource
    DeclarationMapper declarationMapper;

    @Resource
    TDeclarationMatchingMapper tDeclarationMatchingMapper;

    @Resource
    CustomerMianMapper customerMianMapper;

    /**
     * 项目基本信息列表
     *
     * @param pageValidate   分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<ClientCrmProjetDetailListedVo>
     * @author LikeAdmin
     */
    @Override
    public PageResult<ClientCrmProjetDetailListedVo> list(PageValidate pageValidate, ClientCrmProjetDetailSearchValidate searchValidate) {
        Integer page = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<ClientCrmProjetDetail> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("id");
        queryWrapper.orderByAsc("id");

        clientCrmProjetDetailMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:projectName@project_name:str",
//            "=:declarationConditions@declaration_conditions:str",
                "=:projectKey@project_key:str",
                "=:keyElement@key_element:str",
        });

        IPage<ClientCrmProjetDetail> iPage = clientCrmProjetDetailMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ClientCrmProjetDetailListedVo> list = new LinkedList<>();
        for (ClientCrmProjetDetail item : iPage.getRecords()) {
            //项目政策ID
            Integer id = item.getId();
            QueryWrapper<ClientCrmProjetDetailType> queryWrapperp = new QueryWrapper<>();
            queryWrapperp.lambda().eq(StringUtil.isNotEmpty(String.valueOf(id)), ClientCrmProjetDetailType::getProjetId, id);
            List<ClientCrmProjetDetailType> detailTypesList = clientCrmProjetDetailTypeMapper.selectList(queryWrapperp);

            //对应的申报条件内容：条件品类+符号+申报值
            for (ClientCrmProjetDetailType detailType : detailTypesList) {
                Integer typeId = detailType.getDeclarationTypeId();
                QueryWrapper<Declaration> declarationQueryWrapper = new QueryWrapper<>();
                declarationQueryWrapper.lambda().eq(StringUtil.isNotEmpty(String.valueOf(typeId)), Declaration::getId, typeId);
                String detailTypeName = declarationMapper.selectOne(declarationQueryWrapper).getAndsqlName();
                detailType.setAndsqlName(detailTypeName);
            }
            // 设置列表到 record
            item.setDeclarationConditions(detailTypesList);

            ClientCrmProjetDetailListedVo vo = new ClientCrmProjetDetailListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 项目基本信息详情
     *
     * @param id 主键参数
     * @return ClientCrmProjetDetail
     * @author LikeAdmin
     */
    @Override
    public ClientCrmProjetDetailDetailVo detail(Integer id) {
        ClientCrmProjetDetail model = clientCrmProjetDetailMapper.selectOne(
                new QueryWrapper<ClientCrmProjetDetail>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        QueryWrapper<ClientCrmProjetDetailType> queryWrapperp = new QueryWrapper<>();
        queryWrapperp.lambda().eq(StringUtil.isNotEmpty(String.valueOf(id)), ClientCrmProjetDetailType::getProjetId, id);
        List<ClientCrmProjetDetailType> detailTypesList = clientCrmProjetDetailTypeMapper.selectList(queryWrapperp);

        //对应的申报条件内容：条件品类+符号+申报值
        for (ClientCrmProjetDetailType detailType : detailTypesList) {
            Integer typeId = detailType.getDeclarationTypeId();
            QueryWrapper<Declaration> declarationQueryWrapper = new QueryWrapper<>();
            declarationQueryWrapper.lambda().eq(StringUtil.isNotEmpty(String.valueOf(typeId)), Declaration::getId, typeId);
            String detailTypeName = declarationMapper.selectOne(declarationQueryWrapper).getAndsqlName();
            detailType.setAndsqlName(detailTypeName);
        }

        String[] declarationTime = new String[]{model.getDeclarationStart(), model.getDeclarationEnd()};
        model.setDeclarationTime(declarationTime);
        // 设置列表到 record
        model.setDeclarationConditions(detailTypesList);

        ClientCrmProjetDetailDetailVo vo = new ClientCrmProjetDetailDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 项目基本信息新增
     *
     * @param createValidate 参数
     * @author LikeAdmin
     */
    @Override
    public void add(ClientCrmProjetDetailCreateValidate createValidate) {
        ClientCrmProjetDetail model = new ClientCrmProjetDetail();
        model.setProjectName(createValidate.getProjectName());
//        model.setDeclarationConditions(createValidate.getDeclarationConditions());
        model.setProjectKey(createValidate.getProjectKey());
        model.setKeyElement(createValidate.getKeyElement());
        model.setRatingFive(createValidate.getRatingFive());
        model.setRatingFour(createValidate.getRatingFour());
        model.setRatingThree(createValidate.getRatingThree());
        model.setAcceptanceDepartment(createValidate.getAcceptanceDepartment());
        model.setDeclarationStart(createValidate.getDeclarationStart());
        model.setDeclarationEnd(createValidate.getDeclarationEnd());
        model.setAmountSubsidy(createValidate.getAmountSubsidy());
        clientCrmProjetDetailMapper.insert(model);

        if (createValidate.getDeclarationConditions().size() < 0 || createValidate.getDeclarationConditions() == null) {
            return;
        }
        for (ClientCrmProjetDetailType declarationTypeId : createValidate.getDeclarationConditions()) {
            if (declarationTypeId.getDeclarationTypeId() == null) {
                return;
            }
            ClientCrmProjetDetailType ccdmodel = new ClientCrmProjetDetailType();
            ccdmodel.setProjetId(model.getId());
            ccdmodel.setDeclarationTypeId(Integer.valueOf(declarationTypeId.getDeclarationTypeId()));
            clientCrmProjetDetailTypeMapper.insert(ccdmodel);
        }

        // 调用存储过程
        clientCrmProjetDetailTypeMapper.callMatchingProcedure();
    }

    /**
     * 项目基本信息编辑
     *
     * @param updateValidate 参数
     * @author LikeAdmin
     */
    @Override
    public void edit(ClientCrmProjetDetailUpdateValidate updateValidate) {
        ClientCrmProjetDetail model = clientCrmProjetDetailMapper.selectOne(
                new QueryWrapper<ClientCrmProjetDetail>()
                        .eq("id", updateValidate.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setProjectName(updateValidate.getProjectName());
//        model.setDeclarationConditions(updateValidate.getDeclarationConditions());
        model.setProjectKey(updateValidate.getProjectKey());
        model.setKeyElement(updateValidate.getKeyElement());
        model.setRatingThree(updateValidate.getRatingThree());
        model.setRatingFive(updateValidate.getRatingFive());
        model.setRatingFour(updateValidate.getRatingFour());
        model.setAcceptanceDepartment(updateValidate.getAcceptanceDepartment());
        model.setDeclarationStart(updateValidate.getDeclarationStart());
        model.setDeclarationEnd(updateValidate.getDeclarationEnd());
        model.setAmountSubsidy(updateValidate.getAmountSubsidy());
        clientCrmProjetDetailMapper.updateById(model);

        //先删除全部新增后新增
        QueryWrapper<ClientCrmProjetDetailType> queryDelete = new QueryWrapper<>();
        queryDelete.lambda().eq(ClientCrmProjetDetailType::getProjetId, updateValidate.getId());
        clientCrmProjetDetailTypeMapper.delete(queryDelete);

        if (updateValidate.getDeclarationConditions().size() < 0 || updateValidate.getDeclarationConditions() == null) {
            return;
        }
        for (ClientCrmProjetDetailType declarationTypeId : updateValidate.getDeclarationConditions()) {
            if (declarationTypeId.getDeclarationTypeId() == null) {
                return;
            }
            ClientCrmProjetDetailType ccdmodel = new ClientCrmProjetDetailType();
            ccdmodel.setProjetId(model.getId());
            ccdmodel.setDeclarationTypeId(Integer.valueOf(declarationTypeId.getDeclarationTypeId()));
            clientCrmProjetDetailTypeMapper.insert(ccdmodel);
        }

        // 调用存储过程
        clientCrmProjetDetailTypeMapper.callMatchingProcedure();
    }

    /**
     * 项目基本信息删除
     *
     * @param id 主键ID
     * @author LikeAdmin
     */
    @Override
    public void del(Integer id) {
        ClientCrmProjetDetail model = clientCrmProjetDetailMapper.selectOne(
                new QueryWrapper<ClientCrmProjetDetail>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        clientCrmProjetDetailMapper.delete(new QueryWrapper<ClientCrmProjetDetail>().eq("id", id));
        //删除对应政策绑定的申报条件
        QueryWrapper<ClientCrmProjetDetailType> queryDelete = new QueryWrapper<>();
        queryDelete.lambda().eq(ClientCrmProjetDetailType::getProjetId, id);
        clientCrmProjetDetailTypeMapper.delete(queryDelete);

        // 调用存储过程
        clientCrmProjetDetailTypeMapper.callMatchingProcedure();
    }

    /**
     * 项目政策匹配公司
     * <p>
     * 根据项目政策的星级要求，匹配符合条件的公司列表。匹配规则如下：
     * - 三星：匹配数量 >= 三星要求数 且 < 四星要求数
     * - 四星：匹配数量 >= 四星要求数 且 < 五星要求数
     * - 五星：匹配数量 >= 五星要求数
     *
     * @param searchValidate 搜索条件，包含项目ID、筛选星级和公司名称
     * @return 匹配的公司列表
     * @throws IllegalArgumentException 当项目不存在时抛出
     */
    @Override
    public List<CustomerMian> matching(ClientCrmProjetDetailSearchValidate searchValidate) {
        // 1. 获取并验证项目政策信息
        ClientCrmProjetDetail projectDetail = getProjectDetail(searchValidate.getId());

        // 2. 获取匹配的公司及其匹配条数
        List<Map<String, Object>> matchingResults = getMatchingCompanies(searchValidate.getId());

        // 3. 根据星级要求筛选公司
        List<CustomerMian> ratedCompanies = evaluateCompanyRatings(matchingResults, projectDetail);

        // 4. 应用过滤条件
        return filterCompaniesByConditions(ratedCompanies, searchValidate);
    }

    /**
     * 获取项目详情
     */
    private ClientCrmProjetDetail getProjectDetail(Integer projectId) {
        ClientCrmProjetDetail projectDetail = clientCrmProjetDetailMapper.selectOne(
                new QueryWrapper<ClientCrmProjetDetail>()
                        .eq("id", projectId)
                        .last("limit 1"));
        Assert.notNull(projectDetail, "项目不存在!");
        return projectDetail;
    }

    /**
     * 获取匹配的公司及其匹配条数
     */
    private List<Map<String, Object>> getMatchingCompanies(Integer projectId) {
        QueryWrapper<TDeclarationMatching> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId)
                .eq("is_matching", 1)
                .select("customer_id", "COUNT(*) AS ratingCount")
                .groupBy("customer_id");
        return tDeclarationMatchingMapper.selectMaps(queryWrapper);
    }

    /**
     * 根据星级要求评估公司等级
     */
    private List<CustomerMian> evaluateCompanyRatings(List<Map<String, Object>> matchingResults,
                                                      ClientCrmProjetDetail projectDetail) {
        List<CustomerMian> ratedCompanies = new ArrayList<>();

        for (Map<String, Object> result : matchingResults) {
            Long matchCount = Long.valueOf(result.get("ratingCount").toString());
            Integer customerId = Integer.valueOf(result.get("customer_id").toString());

            CustomerMian company = getCompanyById(customerId);
            if (company == null) {
                continue;
            }

            // 评定星级
            if (isValidRating(projectDetail.getRatingFive(), matchCount)) {
                company.setRating(5);
                ratedCompanies.add(company);
            } else if (isValidRating(projectDetail.getRatingFour(), matchCount)) {
                company.setRating(4);
                ratedCompanies.add(company);
            } else if (isValidRating(projectDetail.getRatingThree(), matchCount)) {
                company.setRating(3);
                ratedCompanies.add(company);
            }
        }

        return ratedCompanies;
    }

    /**
     * 根据ID获取公司信息
     */
    private CustomerMian getCompanyById(Integer customerId) {
        return customerMianMapper.selectOne(
                new QueryWrapper<CustomerMian>().eq("id", customerId));
    }

    /**
     * 验证评级是否有效
     */
    private boolean isValidRating(Integer requiredCount, Long matchCount) {
        return requiredCount != null && matchCount >= requiredCount;
    }

    /**
     * 根据条件过滤公司列表
     */
    private List<CustomerMian> filterCompaniesByConditions(List<CustomerMian> companies,
                                                           ClientCrmProjetDetailSearchValidate searchValidate) {
        // 1. 按选定星级过滤
        if (searchValidate.getSelectedRatings() != null && !searchValidate.getSelectedRatings().isEmpty()) {
            companies = companies.stream()
                    .filter(company -> searchValidate.getSelectedRatings().contains(company.getRating()))
                    .collect(Collectors.toList());
        }

        // 2. 按公司名称过滤
        if (StringUtil.isNotEmpty(searchValidate.getCompanyName())) {
            companies = companies.stream()
                    .filter(company -> company.getCompanyName() != null &&
                            company.getCompanyName().contains(searchValidate.getCompanyName()))
                    .collect(Collectors.toList());
        }

        return companies;
    }
}
